﻿using System;
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;

namespace CodeLibrary.IO.Utils
{
    public static class PathUtils
    {
        public static bool IsValidPath(string path)
        {
            string strFolder = Path.GetDirectoryName(path);
            return strFolder != null && (!String.IsNullOrEmpty(path) && Directory.Exists(strFolder));
        }

        public static string GetAbsolutePath(string basePath, string relativePath)
        {
            string[] parts = relativePath.Split(new[] { "\\", "/" }, StringSplitOptions.None);
            string result = basePath;
            foreach (string part in parts)
            {
                if (part == "..")
                {
                    result = Path.GetDirectoryName(result);
                }
                else if (part != ".")
                {
                    if (result == null)
                    {
                        throw new NullReferenceException("");
                    }
                    result = Path.Combine(result, part);
                }
            }
            return result;
        }

        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public static void ExplorePath(string path)
        {
            if (File.Exists(path))
            {
                Process.Start(path);
            }
            else if (Directory.Exists(path))
            {
                Process.Start(path);
            }
            else if (Uri.IsWellFormedUriString(path, UriKind.Absolute))
            {
                Process.Start(path);
            }
            else
            {
                throw new ArgumentException(path + "不存在！");
            }
        }
    }
}
